const express = require('express');
const path = require('path');
const http = require('http');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = socketIo(server, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"]
  }
});

// 中间件配置
app.use(express.json());
app.use(express.static(path.join(__dirname, '../frontend/dist')));

// 静态文件服务
app.use('/downloads', express.static(path.join(__dirname, '../downloads')));

// API路由
app.use('/api/git', require('./routes/git'));
app.use('/api/build', require('./routes/build'));
app.use('/api/download', require('./routes/download'));
app.use('/api/miniprogram', require('./routes/miniprogram'));

// WebSocket连接管理
const buildSessions = new Map();

io.on('connection', (socket) => {
  console.log('🔌 客户端连接:', socket.id);
  
  // 加入构建会话
  socket.on('join-build-session', (projectId) => {
    socket.join(`build-${projectId}`);
    console.log(`📋 客户端 ${socket.id} 加入构建会话: ${projectId}`);
  });
  
  // 离开构建会话
  socket.on('leave-build-session', (projectId) => {
    socket.leave(`build-${projectId}`);
    console.log(`📋 客户端 ${socket.id} 离开构建会话: ${projectId}`);
  });
  
  socket.on('disconnect', () => {
    console.log('🔌 客户端断开连接:', socket.id);
  });
});

// 导出io实例供其他模块使用
app.set('io', io);

// 初始化日志管理器
const logManager = require('./utils/logManager');
logManager.init(io);

// 全局进程错误处理 - 防止服务挂掉
process.on('uncaughtException', (error) => {
  console.error('🚨 未捕获的异常:', error);
  console.error('Stack:', error.stack);
  
  // 记录错误但不退出进程
  if (logManager) {
    logManager.sendSystemLog('uncaught-exception', {
      message: '系统检测到未捕获异常，已自动恢复',
      error: error.message,
      stack: error.stack
    });
  }
  
  // 不调用 process.exit(1) - 让服务继续运行
});

process.on('unhandledRejection', (reason, promise) => {
  console.error('🚨 未处理的Promise拒绝:', reason);
  console.error('Promise:', promise);
  
  // 记录错误但不退出进程
  if (logManager) {
    logManager.sendSystemLog('unhandled-rejection', {
      message: '系统检测到未处理的Promise拒绝，已自动恢复',
      reason: reason,
      promise: promise
    });
  }
});

// Express全局错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({ error: '服务器内部错误' });
});

// 前端路由处理
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, '../frontend/dist/index.html'));
});

const PORT = process.env.PORT || 9999;

server.listen(PORT, () => {
  console.log(`🚀 服务器运行在端口 ${PORT}`);
  console.log(`📱 前端地址: http://localhost:${PORT}`);
  console.log(`🔧 API地址: http://localhost:${PORT}/api`);
});

module.exports = { app, server, io };
